package com.example.music;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MusicListActivity extends AppCompatActivity {
    //定义UI组件对象
    ListView list_music;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        //初始化UI组件对象
        initViews();
    }
    private void initViews() {
        list_music=this.findViewById(R.id.list_music);
        //加载本地音乐文件列表
        getAllFiles();
        SimpleAdapter adapter = new SimpleAdapter(
                MusicListActivity.this,
                MusicData.data,
                R.layout.item_layout,
                new String[]{"name","date"},
                new int[]{R.id.txt_name,R.id.txt_date}

        );
        list_music.setAdapter(adapter);
        //给音乐列表添加单击事件
        list_music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(MusicListActivity.this,MusicPlayActivity.class);
                MusicData.index=position;
                startActivity(intent);
            }
        });
    }
    //转换显示的日期
    private String showDate(long date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        return sdf.format(new Date(date));
    }
    //读取sd卡上的音乐文件
    private void getAllFiles(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music/");
            File musics[] = file.listFiles();
            if(musics.length!=0) {
                //发现音乐文件，开始读取列表
                HashMap<String, String> map = null;
                for (int i = 0; i < musics.length; i++) {
                    map = new HashMap<>();
                    map.put("path",musics[i].getAbsolutePath());
                    map.put("name", musics[i].getName());
                    map.put("date", "" + showDate(musics[i].lastModified()));
                    MusicData.data.add(map);
                    Log.d("music", "getAllFiles:" + musics[i].getName());
                }
            }else{
                Log.d("music","该文件夹下没有发现音乐文件");
            }
        }else{
            Log.d("music","当前手机没有存储卡");
        }
    }

}